package com.yeban.javase.day19;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Test1 {

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        Socket socket = null;
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            // 连接服务端
            socket = new Socket("192.168.0.152", 8899);
            System.out.println("客户端正常启动！");

            // 循环发消息
            while(true) {
                String str = sc.nextLine();
                if (str.equals("exit")) {
                    break;
                }
            }

            // 写消息
            out = new PrintWriter(socket.getOutputStream(), true);

            out.println("你好！我是孙禀鉴~");
            System.out.println("消息已发送到服务器。");


            // 客户端也可以写消息
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String s = in.readLine();
            System.out.println("服务端接收到消息：" + s);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
            if (socket != null) try {
                socket.close();
            } catch (IOException ignored) {

            }
        }
    }
}
